//
//  ForgotPasswordVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/8/12.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "ForgotPasswordVC.h"

@interface ForgotPasswordVC ()<UITextFieldDelegate>{
    dispatch_source_t _timer;
    BOOL _isSMSon;
}

@property UITextField *iphoneNumber;
@property UITextField *smsText;
@property UITextField *newsPassword;
@property UIButton *clearBtn;
@property UIButton *hiddenON;
@property UIButton *passwordOn;
@property UIButton *login;


@end

@implementation ForgotPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavTitle:@"修改密码" titleColor:[UIColor blackColor] font:font17];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initView];
    
    
    _iphoneNumber.text = [userDefaults objectForKey:@"useriPhone"];

}

- (void)viewWillDisappear:(BOOL)animated{
    if(_timer!=nil){
        dispatch_source_cancel(_timer);
    }
}

- (void)initView{
    
    _iphoneNumber = [[UITextField alloc] init];
    _iphoneNumber.placeholder = @"请输入手机号";
    _iphoneNumber.font = [UIFont systemFontOfSize:16*H];
    _iphoneNumber.textColor = UIColorFromRGB(0x333333);
    _iphoneNumber.delegate = self;
    _iphoneNumber.enabled = NO;
    _iphoneNumber.returnKeyType = UIReturnKeyDone;
    

    [self.view addSubview:_iphoneNumber];
    _iphoneNumber.sd_layout
    .leftSpaceToView(self.view, GETWITH(40))
    .topSpaceToView(self.view, GETHEIGHT(102))
    .rightSpaceToView(self.view, GETWITH(150))
    .heightIs(GETHEIGHT(60));
    
    _clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _clearBtn.hidden = YES;
    [_clearBtn setImage:[UIImage imageNamed:@"login_icon3_input_nor"] forState:UIControlStateNormal];
    [_clearBtn addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_clearBtn];
    _clearBtn.sd_layout
    .rightSpaceToView(self.view, GETWITH(52))
    .centerYEqualToView(_iphoneNumber)
    .widthIs(GETWITH(40))
    .heightEqualToWidth();

    
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view1];
    view1.sd_layout
    .leftSpaceToView(self.view, GETWITH(40))
    .rightSpaceToView(self.view, GETWITH(40))
    .topSpaceToView(_iphoneNumber, GETHEIGHT(28))
    .heightIs(GETHEIGHT(1));
    
    _smsText = [[UITextField alloc] init];
    
    _smsText.placeholder = @"请输入验证码";
    _smsText.font = [UIFont systemFontOfSize:16*H];
    _smsText.textColor = UIColorFromRGB(0x333333);
    _smsText.delegate = self;
    
    _smsText.returnKeyType = UIReturnKeyDone;

    [self.view addSubview:_smsText];
    _smsText.sd_layout
    .leftSpaceToView(self.view, GETWITH(46))
    .topSpaceToView(view1, GETHEIGHT(62))
    .rightSpaceToView(self.view, GETWITH(150))
    .heightIs(GETHEIGHT(60));
    
    _hiddenON = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [_hiddenON addTarget:self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];
    [_hiddenON setTitle:@"发送验证码" forState:UIControlStateNormal];
    [_hiddenON setTitleColor:UIColorFromRGB(0xe64463) forState:UIControlStateNormal];
    _hiddenON.backgroundColor = [UIColor whiteColor];
    _hiddenON.titleLabel.font = font14;


    [self.view addSubview:_hiddenON];
    _hiddenON.sd_layout
    .rightEqualToView(view1)
    .centerYEqualToView(_smsText)
    .widthIs(GETWITH(204))
    .heightIs(GETHEIGHT(56));
    _hiddenON.layer.borderWidth = 1;
    _hiddenON.layer.borderColor = UIColorFromRGB(0xe64463).CGColor;
    _hiddenON.sd_cornerRadius = @(GETHEIGHT(28));

    
    UIView *view2 = [[UIView alloc] init];
    view2.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view2];
    view2.sd_layout
    .leftEqualToView(view1)
    .rightEqualToView(view1)
    .topSpaceToView(_smsText, GETHEIGHT(29))
    .heightIs(GETHEIGHT(1));
    
    _newsPassword = [[UITextField alloc] init];
    _newsPassword.placeholder = @"请输入6-12位登录密码";
    _newsPassword.font = [UIFont systemFontOfSize:16*H];
    _newsPassword.textColor = UIColorFromRGB(0x333333);
   
    _newsPassword.delegate = self;
    _newsPassword.secureTextEntry  = YES;
    _newsPassword.returnKeyType = UIReturnKeyDone;

    [self.view addSubview:_newsPassword];
    _newsPassword.sd_layout
    .leftSpaceToView(self.view, GETWITH(46))
    .topSpaceToView(view2, GETHEIGHT(62))
    .rightSpaceToView(self.view, GETWITH(150))
    .heightIs(GETHEIGHT(60));
    
    _passwordOn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_passwordOn setImage:[UIImage imageNamed:@"login_icon5_input_nor"] forState:UIControlStateNormal];
    [_passwordOn addTarget:self action:@selector(isNoOrYes:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_passwordOn];
    _passwordOn.sd_layout
    .rightEqualToView(view2)
    .centerYEqualToView(_newsPassword)
    .widthIs(GETWITH(100))
    .heightIs(GETHEIGHT(30));
    
    UIView *view3 = [[UIView alloc] init];
    view3.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view3];
    view3.sd_layout
    .leftEqualToView(view1)
    .rightEqualToView(view1)
    .topSpaceToView(_newsPassword, GETHEIGHT(28))
    .heightIs(GETHEIGHT(1));
    
    UILabel *title = [[UILabel alloc] init];
    title.text = @"下次可以直接通过手机号和新密码登录";
    title.textColor = [UIColor grayColor];
    title.font = font12;
    title.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:title];
    title.sd_layout.leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0)
    .topSpaceToView(view3, GETHEIGHT(30))
    .autoHeightRatio(0);
    
    _login = [UIButton buttonWithType:UIButtonTypeCustom];
    [_login setBackgroundImage:[UIImage imageNamed:@"login_btn_defauit_nor"] forState:UIControlStateNormal];
    [_login addTarget:self action:@selector(ONLogin:) forControlEvents:UIControlEventTouchUpInside];
   // _login.enabled = NO;
    [self.view addSubview:_login];
    _login.sd_layout
    .topSpaceToView(view3, GETHEIGHT(160))
    .heightIs(GETHEIGHT(100))
    .leftEqualToView(view1)
    .rightEqualToView(view1);
    
}


//注意：事件类型是：`UIControlEventEditingChanged`
-(void)passConTextChange:(id)sender{
    UITextField* target=(UITextField*)sender;
    NSLog(@"%@",target.text);
}


- (void)clear:(id)sender {
    _iphoneNumber.text = @"";
    _smsText.text = @"";
    _newsPassword.text = @"";
    [_iphoneNumber becomeFirstResponder];
}

- (void)isNoOrYes:(UIButton *)sender {
    
    _passwordOn.selected = !sender.selected;
    if(_passwordOn.selected){
        [_passwordOn setImage:[UIImage imageNamed:@"login_icon4_input_nor"] forState:UIControlStateNormal];
        _newsPassword.secureTextEntry = NO;
    }else{
        [_passwordOn setImage:[UIImage imageNamed:@"login_icon5_input_nor"] forState:UIControlStateNormal];
        _newsPassword.secureTextEntry = YES;
        
    }
}

-(void)startTime{
    if(_iphoneNumber.text.length<1){
        [AlertUtils showToastWithMessage:@"请先填写手机号码" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
        return;
        
    }else if (![ToolClass valiMobile:_iphoneNumber.text]){
        [AlertUtils showToastWithMessage:@"请输入正确的手机号码" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
        return;
        
    }
    __weak typeof(self)weakself = self;
    
    [[PPHttpRequsetData shareInstance] requestStyle:Request_GET URL:@"/ShopApi/Login/sendVerify" parameter:@{@"phone":_iphoneNumber.text	} successBlock:^(PPHttpRequest *request, id responseObj) {
        
        [weakself time];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:1.0 beIndeter:NO];
    } ];
    
    
}

-(void)time{
    _isSMSon = YES;
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置（倒计时结束后调用）
                [_hiddenON setTitle:@"重新发送" forState:UIControlStateNormal];
                //设置不可点击
                _hiddenON.userInteractionEnabled = YES;
                _hiddenON.backgroundColor = [UIColor whiteColor];
                _hiddenON.layer.borderColor = UIColorFromRGB(0xe64463).CGColor;
                [_hiddenON setTitleColor:UIColorFromRGB(0xe64463) forState:UIControlStateNormal];
                
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [_hiddenON setTitle:[NSString stringWithFormat:@"重新获取%@(s)",strTime] forState:UIControlStateNormal];
                //设置可点击
                _hiddenON.userInteractionEnabled = NO;
                _hiddenON.backgroundColor = [UIColor whiteColor];
                [_hiddenON setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                _hiddenON.layer.borderColor = [UIColor grayColor].CGColor;
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
    
}

- (void)ONLogin:(id)sender {
    [_newsPassword resignFirstResponder];
    [_iphoneNumber resignFirstResponder];
    
    if(_iphoneNumber.text.length<1){
        [AlertUtils showToastWithMessage:@"请先填写手机号码" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
        return;
    }
    if(_newsPassword.text.length<1){
        [AlertUtils showToastWithMessage:@"请先填写密码" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    
    if(_newsPassword.text.length < 6 || _newsPassword.text.length > 12){
        [AlertUtils showToastWithMessage:@"请填入正确的手机号" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    
    if(![ToolClass valiMobile:_iphoneNumber.text]){
        [AlertUtils showToastWithMessage:@"请填入正确的手机号" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    NSDictionary *dic = @{@"phone":_iphoneNumber.text,@"verifyCode":_smsText.text,@"password":_newsPassword.text};
    __weak typeof(self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Login/changePassword" parameter:dic successBlock:^(PPHttpRequest *request, id responseObj) {
        
       // [[AppDelegate delegate] LoginVC];
        [weakself.navigationController popToRootViewControllerAnimated:YES];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
       [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:1.0 beIndeter:NO];
    }];
    
   
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if(textField == _smsText){
        if(_isSMSon == NO)
        {
            [textField resignFirstResponder];
          [AlertUtils showToastWithMessage:@"请先发送验证码" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
          return;
        }
    }
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
    if(_newsPassword.text.length >0 && _iphoneNumber.text.length > 0 && _smsText.text.length>0){
        [_login setBackgroundImage:[UIImage imageNamed:@"login_btn_defauit_hig"] forState:UIControlStateNormal];
       // _login.enabled = YES;
    }else{
        [_login setBackgroundImage:[UIImage imageNamed:@"login_btn_defauit_nor"] forState:UIControlStateNormal];
        //_login.enabled = NO;
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    return YES;
}

@end
